package at.jku.se.pr.quickshopper.activities;

import java.math.BigDecimal;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import at.jku.se.pr.quickshopper.R;
import at.jku.se.pr.quickshopper.R.id;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import at.jku.se.pr.quickshopper.model.Article;
import at.jku.se.pr.quickshopper.network.ServerConnection;
import at.jku.se.pr.quickshopper.util.Utils;
import at.jku.se.pr.quickshopper.zbar.ZBarConstants;
import at.jku.se.pr.quickshopper.zbar.ZBarScannerActivity;

/**
 * class which implements the view which shows you the overall price you have to pay
 * after clicking on the "Kassabarcode scannen"-Button => the camera starts
 */
public class PayActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
		
		Intent i = getIntent();
		Double d = i.getDoubleExtra("gesamtpreis", 0.00d);
		Log.e("", String.valueOf(d));
		
		TextView preis = (TextView) findViewById(R.id.textView1);
		BigDecimal bigDec = new BigDecimal(d.doubleValue());
		preis.setText(Utils.euroStringFormatter(bigDec));
		
		Button btn_kassabarcode = (Button) findViewById(id.btn_starteKassabarcodeScan);
		btn_kassabarcode.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				CheckBox pay = (CheckBox) findViewById(id.payCheckbox);
				if (pay.isChecked()) {
					Intent intent = new Intent(PayActivity.this, ZBarScannerActivity.class);
					startActivityForResult(intent, Constants.ZBAR_SCANNER_REQUEST);
				} else {
					LayoutInflater inflater = getLayoutInflater();
					View checkView = inflater.inflate(R.layout.check_view_dialog_layout, null);
					
					AlertDialog.Builder builder = new AlertDialog.Builder(PayActivity.this);
					builder.setTitle("Haben Sie alle Produkte erfasst?");
					builder.setView(checkView);
					
					builder.setNegativeButton("Ja", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int arg1) {
							dialog.cancel();
							Intent intent = new Intent(PayActivity.this, ZBarScannerActivity.class);
							startActivityForResult(intent, Constants.ZBAR_SCANNER_REQUEST);
						}
					});
					
					builder.setPositiveButton("Nein", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int arg1) {
							dialog.cancel();
							Intent intent = new Intent(PayActivity.this, ShoppingActivity.class);
							intent.putExtra("from", 2);
							startActivity(intent);
						}
					});
					
					builder.create().show();
				}
			}
			
		});
		
	}
	
	/**
	 * creates a new Purchase-Entry(JSONArray) for the database if the barcode-scan was succesful 
	 */
	private void buildJsonArray() {
		JSONArray array = new JSONArray();
		
		try {
			JSONObject o = new JSONObject();
			o.put("kunde_id", Constants.customer);
			array.put(o);
			
			o = new JSONObject();
			o.put("filiale", Constants.scanResult);
			array.put(o);
			
			o = new JSONObject();
			o.put("menge", ShoppingActivity.saver.getModel().getSumAmountFromList());
			array.put(o);
			
			o = new JSONObject();
			o.put("gesamtpreis", ShoppingActivity.saver.getModel().getSumPriceFromList());
			array.put(o);
			
			ArrayList<Article> list = ShoppingActivity.saver.getModel().getList();
			for (Article a : list) {
				o = new JSONObject();
				o.put("ean", a.getmEAN());
				o.put("menge", a.getmAmount());
				o.put("preis", a.getmPrice().doubleValue());
				array.put(o);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		String arrayString = array.toString();
		Log.e("", "arrayString: " + arrayString);
		
		ServerConnection conn = new ServerConnection(arrayString);
		conn.start();
		
		try {
			conn.join(Constants.NETWORK_TIMEOUT);
		} catch (InterruptedException e) { 
			e.printStackTrace();
		}
		
		String res = conn.getResult();
		Log.e("", "res: " + res);
		
		if (res.equalsIgnoreCase("error")) {
			Toast.makeText(this, "Server/Datenbank ist derzeit in Wartung. Sorry!", Toast.LENGTH_SHORT).show();
		} else {
			// ueberpruefen, ob Produkte erfolgreich an Server gesendet und in DB eingetragen worden sind
			if (res.equals("ok")) {
				Toast.makeText(this, "Deine Produkte wurden erfolgreich verarbeitet!", Toast.LENGTH_LONG).show();
				Intent i = new Intent(PayActivity.this, EndActivity.class);
				startActivity(i);
			} else {
				Toast.makeText(this, "Es ist ein Fehler aufgetreten, bitte noch einmal Kassa-Barcode scannen!", Toast.LENGTH_LONG).show();
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		boolean camUnav = false;
		if (resultCode == RESULT_OK) {
	        Log.e("", "gescannter EAN-Barcode: " + data.getStringExtra(ZBarConstants.SCAN_RESULT));
	        Constants.scanResult = Long.parseLong(data.getStringExtra(ZBarConstants.SCAN_RESULT));
	    } else if(resultCode == RESULT_CANCELED) {
	        Toast.makeText(this, "Camera unavailable", Toast.LENGTH_SHORT).show();
	        camUnav = true;
	    }
		
	    if (!camUnav) {
	    	String str = Constants.createJson("kassabarcode");
	    	if (str.equalsIgnoreCase("error")) {
				Toast.makeText(this, "Server/Datenbank ist derzeit in Wartung. Sorry!", Toast.LENGTH_SHORT).show();
			} else {
				boolean cashdeskOK = false;
				try {
					// daraus wieder ein JSONObject machen
					JSONObject cashdesk = new JSONObject(str);
					if (cashdesk.getString("kassa").equalsIgnoreCase("ok")) {
						cashdeskOK = true;
					} else {
						Toast.makeText(this, "Falscher Barcode, bitte den Barcode an der Kassa scannen!", Toast.LENGTH_SHORT).show();
						cashdeskOK = false;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (cashdeskOK) {
					buildJsonArray();
				}
			}
	    }
	}
	
}
